package com.fansl.allround.auth.provider.social.weibo.api;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.fansl.allround.auth.provider.social.weibo.bean.WeiboToken;
import com.fansl.allround.auth.provider.social.weibo.bean.WeiboUserInfo;
import com.fansl.allround.auth.provider.social.weibo.config.WeiboOauthConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author fansl
 * @Description: TODO
 * @date 2019/10/16 15:12
 */
@Slf4j
@Service
public class WeiboApiImpl implements WeiboApi {
    /**
     * 将用户导向认证服务器 https://open.weibo.com/wiki/Oauth2/authorize
     */
    public static final String URL_AUTHORIZE = "https://api.weibo.com/oauth2/authorize" +
            "?client_id=%s&redirect_uri=%s&state=thrid";
    /**
     * 随带授权码获取用户令牌accessToken https://open.weibo.com/wiki/Oauth2/access_token
     */
    public static final String URL_ACCESS_TOKEN = "https://api.weibo.com/oauth2/access_token" +
            "?grant_type=%s&client_id=%s&client_secret=%s&code=%s&redirect_uri=%s";
    /**
     * 获取用户信息 父类会自动携带accessToken https://open.weibo.com/wiki/Oauth2/get_token_info
     */
    public final static String URL_GET_USER_INFO = "https://api.weibo.com/2/users/show.json?access_token=%s&uid=%s";

    @Resource
    private WeiboOauthConfig weiboOauthConfig;

    @Override
    public WeiboUserInfo getUserInfo(String accessToken, String uid) {
        String url = String.format(URL_GET_USER_INFO, accessToken, uid);
        String userInfoResult = HttpUtil.createGet(url).execute().body();
        log.info("weibo getUserInfo json response:{}", userInfoResult);
        WeiboUserInfo userInfo = JSONObject.parseObject(userInfoResult, new TypeReference<WeiboUserInfo>() {
        });
        return userInfo;

    }

    @Override
    public WeiboToken getAccessToken(String code) {
        String grantType = "authorization_code";
        String redirectUri = URLUtil.encode(weiboOauthConfig.getRedirectUri(), "utf-8");
        String url = String.format(URL_ACCESS_TOKEN, grantType,
                weiboOauthConfig.getAppId(), weiboOauthConfig.getAppSecret(), code, redirectUri);
        String result = HttpUtil.createPost(url).execute().body();
        log.info("weibo getAccessToken json response:{}", result);
        return JSONObject.parseObject(result, new TypeReference<WeiboToken>() {
        });
    }
}
